<template>
  <div class="comdiv">

    <happy-scroll  color="#ccc" size="5" class="layout-scrollbar__wrap"  resize hide-horizontal>
      <div class="con" ref="bgImage">
        <!-- search1 -->
        <div class="filter-container">
          <el-row>
            <el-col :span="4">
              <div style="margin-left: 2%">
                <el-select v-model="listQuery.areaId" placeholder="地区" @change="areaChange" style="width: 100%">
                  <el-option
                    v-for="item in selectAreas"
                    :key="item._id"
                    :label="item.areaName"
                    :value="item._id">
                  </el-option>
                </el-select>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                  <el-select v-model="listQuery.companyId" placeholder="公司" @change="companyChange" style="width: 100%">
                   <el-option
                     v-for="item in selectCompany"
                     :key="item._id"
                     :label="item.companyName"
                     :value="item._id">
                   </el-option>
                 </el-select>
              </div>
            </el-col>
            <el-col :span="14">

     <!--         <el-input  style="width: 300px;" :placeholder="placeholder" v-model="listQuery.searchText"></el-input>
              <el-button  type="primary" v-waves icon="el-icon-search" @click="handleFilter">
                搜索
              </el-button>-->
            </el-col>
            <el-col  :span="2">
              <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="success" icon="el-icon-plus">添加
              </el-button>
            </el-col>
          </el-row>
        </div>
        <!--table-->
        <el-table :data="list" v-loading.body="listLoading" border fit highlight-current-row style="width: 100%">
          <el-table-column align="center" label="序号" width="100">
            <template slot-scope="scope"><span>{{scope.row.px}}</span></template>
          </el-table-column>
          <el-table-column align="center" label="id" width="100">
            <template slot-scope="scope"><span>{{scope.row._id}}</span></template>
          </el-table-column>

          <el-table-column align="center" label="公司" prop="companyName">
            <template slot-scope="scope"><span>{{scope.row.company.companyName}}</span></template>
          </el-table-column>
          <el-table-column align="center" label="部门" prop="departmentName">
            <template slot-scope="scope"><span>{{scope.row.departmentName}}</span></template>
          </el-table-column>
          <el-table-column align="center" label="创建时间" prop="createdTime">
            <template slot-scope="scope"><span>{{scope.row.createdTime}}</span></template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <!--<el-button type="success" plain @click="handleUpdate(scope.row)" size="small">-->
              <el-button type="primary" plain @click="handleUpdate(scope.row)" size="small">修改</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--add-->
        <el-dialog :title="dialogStatus=='create'?'添加部门':'修改部门'" :visible.sync="dialogFormVisible">
          <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="100px"
                   style='width: 450px; margin-left:50px;'>
            <el-form-item label="部门名" prop="departmentName">
              <el-input v-model="temp.departmentName"></el-input>
            </el-form-item>
          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button v-if="dialogStatus=='create'" type="primary" @click="createData" id="cfmbtm1">添加</el-button>
            <el-button v-else type="primary" @click="updateData" id="cfmbtm2">修改</el-button>
          </div>
        </el-dialog>
        <!--edit-->
        <!--分页组件-->
        <!--      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size"
                          @pagination="getList"/>-->

      </div>

    </happy-scroll>


  </div>
</template>

<script>

  /* eslint-disable */
  import {
    fetchGet,
    areasAll,
    departAll,
    createOne,
    updateOneNoId,
    deleteOnePut
  } from '@/api/common'
  import {disableBtn,ERRS, SUCS} from '@/utils'
  import waves from '@/directive/waves' // 水波纹指令
  // import Pagination from '@/components/Pagination'
  // import $ from 'jquery'

  export default {
    name: 'departmentList',
    directives: {waves},
    inject: ['_company'],
    // search2 引入 and search3 声明
    components: {},

    data() {
      return {
        list: null,
        // total: 110,
        // px: null, //最大序号
        listLoading: false,
        placeholder: '部门', //search4
        selectCompany:{},
        selectAreas:{},
        listQuery: {
          page: 1,
          size: 10, //每页几条
          number: 0, //当前页为第1页,从0计算
          searchText: '',
          areaId: '',
          companyId: this._company._id,
        },
        //弹出层
        dialogFormVisible: false,
        dialogStatus: '',
        tempDetail: {},
        temp: {},   //保存添加,编辑后提交的信息
        rules: {
          departmentName: [
            {required: true, message: '请输入部门名', trigger: 'blur'}
          ],
        },
      }
    },
    watch: {},
    mounted() {
      if(!this._company)
        ERRS('未获取到用户公司信息!')
      else{
        console.log(this._company._id,this._company.companyName)
        this.selectCompany=[{_id:this._company._id,companyName:this._company.companyName}]
      }

      this.getList();
      this.getAll();
    },
    methods: {
      ////search
      handleFilter(val) {
        console.log(val);
        // this.listQuery.searchText = val;
        this.getList()
      },
      areaChange(areaId){
        this.listQuery.companyId=undefined
        fetchGet(`auth/companies/areas/${areaId}/all`).then(res => {
          if (res.code == 0) {
            this.selectCompany = res.data;
          } else {
            ERRS('地区调用Err: '+res.message)
          }
        })
      },
      companyChange(){
        this.getList()
      },
      getAll(){
        //地区
        areasAll().then(res => {
          if (res.code == 0) {
            this.selectAreas = res.data;
          } else {
            ERRS('地区调用Err: '+res.message)
          }
        })
      },

      getList() {
        if(!this.listQuery.companyId){
          ERRS('请选择公司!');return;
        }

        this.listLoading = true;
        departAll(this.listQuery.companyId).then(res => {
          console.log(res);
          if (res.code == 0) {
            let dat = res.data
            // this.listQuery.size = dat.size ? dat.size : //每页几条
            // this.listQuery.page = dat.page ? dat.page : //当前页为第1页
            this.list = dat;
            let insIndex = this.listQuery.size * (this.listQuery.page - 1);
            this.list = this.list.map((v, index) => {
              this.$set(v, 'px', insIndex + index + 1);
              // this.$set(v, 'roles',insIndex+index+1);
              this.px = insIndex + index + 1; //最大序号
              return v
            });
            this.$nextTick()
          } else {
            ERRS(res.message)
          }
          this.listLoading = false
        })
      },
      handleCreate() {
        if(!this.listQuery.companyId) {ERRS('请选择公司!');return;}
        this.temp={
          departmentName:'',
        };
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      //添加提交
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            disableBtn('cfmbtm1');
            createOne(`auth/companies/${this.listQuery.companyId}/departments`, this.temp).then(res => {
              if (res.code === 0) {
                SUCS('添加成功!')
                this.getList();
              } else {
                ERRS(res.message)
              }
              this.dialogFormVisible = false
            })
          }
        })
      },
      //详情修改
      handleUpdate(row) {
        // console.log(row);return;

        this.temp = {
          departmentName:row.departmentName,
          id:row._id,
          cid:row.company._id
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate();
        })
      },
      //修改提交
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            disableBtn('cfmbtm2');
            // delete tempData.createdTime;
            updateOneNoId(`auth/companies/${this.temp.cid}/departments/${this.temp.id}`, this.temp).then(res => {
              if (res.code === 0) {
                SUCS('修改成功!')
                this.getList();
              } else {
                ERRS(res.message)
              }
              this.dialogFormVisible = false
            })
          }
        })
      },
      //删除
      handleDelete(row) {
        console.log(row);
        this.$msgbox({
          // title: '删除',
          message: '确定要删除吗?',
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(action => {
          deleteOnePut(`auth/companies/${row.company._id}/departments/freeze`,row._id).then(res => {
            if (res.code === 0) {
              this.getList();
              SUCS('删除成功!')
            } else {
              ERRS(res.message)
            }
            this.dialogFormVisible = false
          })
        });
      },

    }
  }
</script>

<style  rel="stylesheet/scss" lang="scss">
  @import './comp/index.scss';
</style>
